package com.csist.dao;

import com.csist.model.User;
import com.csist.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 注册
     * @param name 用户名
     * @param pwd 密码
     * @return true-->注册成功 false-->注册失败
     */
    public boolean register(String name, String pwd){
        Connection conn = JDBCUtil.getConnection();
        String sql = "insert into user value (default ,?,?)";
        PreparedStatement ps = null;
        boolean isSucceed = false;

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,pwd);
            if(ps.executeUpdate()==1){
                isSucceed = true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(conn,ps);
        }
        return isSucceed;
    }

    /**
     * 登录
     * @param name 用户名
     * @param pwd 密码
     * @return true-->登录成功 false-->登录失败
     */
    public User login(String name, String pwd){
        Connection conn = JDBCUtil.getConnection();
        String sql = "select * from user where u_name = ? and u_pwd = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = new User();

        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,pwd);
            rs = ps.executeQuery();
            if (rs.next()){
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setPsw(rs.getString(3));
            } else {
                user = null;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return user;
    }
}
